﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using IPMsgMoTest.ViewModels;

namespace IPMsgMoTest
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.conversation.DataContext = ViewManager.Instance;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.BindData();
                System.Threading.ThreadPool.QueueUserWorkItem(
                result =>
                {
                    this.Initial();
                });
            }
        }

        private void Initial()
        {
            try
            {
                IPMSG.IPMsgManager.Instance.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("启动失败,{0}. 请尝试重新启动", ex.Message));
            }
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox listbox = sender as ListBox;
            if (listbox.SelectedIndex != -1)
            {
                string next = string.Format("/ChatPage.xaml?hostname={0}", (listbox.SelectedItem as ItemViewModel).HostName);
                Uri uri = new Uri(next, UriKind.Relative);
                this.NavigationService.Navigate(uri);
            }

            listbox.SelectedIndex = -1;
        }

        private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            ListBox listbox = sender as ListBox;
            if (listbox.SelectedIndex != -1)
            {
                string next = string.Format("/ChatPage.xaml?hostname={0}", (listbox.SelectedItem as ChatViewModel).Hostname);
                Uri uri = new Uri(next, UriKind.Relative);
                this.NavigationService.Navigate(uri);
            }

            listbox.SelectedIndex = -1;
        }
    }
}